package com.hk.commons.img;

import com.hk.commons.util.StringUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;


/**
 * @author Kevin
 */
public abstract class FontUtil {

    public static final String MICROSOFT_YAHEI = "Microsoft YaHei";

    public static Font YAHEI_PLAIN_20 = new Font(MICROSOFT_YAHEI, Font.PLAIN, 20);

    /**
     * 创建字体
     *
     * @param name  字体名称
     * @param style 字体 Style
     * @param size  字体大小
     */
    public static Font newFont(String name, int style, int size) {
        return new Font(StringUtils.defaultIfEmpty(name, MICROSOFT_YAHEI), style, size);
    }

    /**
     * 根据字体文件来生成Font类
     *
     * @param fontPath 字体路径
     * @param style    样式
     * @param size     大小
     */
    public static Font getFont(String fontPath, int style, int size) throws IOException, FontFormatException {
        return getFont(new FileSystemResource(fontPath), style, size);
    }

    /**
     * 根据字体文件来生成Font类
     *
     * @param fontPath 字体路径
     * @param style    样式
     * @param size     大小
     */
    public static Font getFont(Resource resource, int style, int size) throws IOException, FontFormatException {
        try (var inputStream = resource.getInputStream()) {
            var font = Font.createFont(Font.TRUETYPE_FONT, inputStream);
            return font.deriveFont(style, size);
        }
    }


    /**
     *
     */
    public static FontMetrics getFontMetric(Font font) {
        var bf = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
        var g2d = GraphicUtil.getG2d(bf);
        g2d.setFont(font);
        return g2d.getFontMetrics();
    }
}
